/**
 * Copyright 2011 FeedDreamwork SIG
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.feeddreamwork.ui;

import java.io.*;

import javax.servlet.http.*;

import org.feeddreamwork.*;
import org.feeddreamwork.pubsubhubbub.*;

import com.google.appengine.api.users.*;

public class DeleteFeedServlet extends HttpServlet {
	private static final long serialVersionUID = -1536148597715252482L;

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");

		FeedInfoRepository feedInfoRepo = new FeedInfoRepository();
		FeedResultRepository feedResultRepo = new FeedResultRepository();
		try {
			String feedId = req.getParameter("feedid");
			FeedInfo feedInfo = feedInfoRepo.getFeedInfo(feedId);
			if (feedInfo == null) {
				resp.sendError(400);
				return;
			}
			if (feedInfo.hasModifyPermission(UserServiceFactory
					.getUserService())) {
				feedInfoRepo.deleteObject(feedInfo);
				FeedResult feedResult = feedResultRepo.getFeedResult(feedInfo
						.getFeedId());
				if (feedResult != null)
					feedResultRepo.deleteObject(feedResult);
				MiniCache.remove("FEED_" + feedId);
				MiniCache.remove("FEEDINFOS");
				PSHBUtils.unsubscribe(ApplicationProperty.HOST_NAME + "/feed/"
						+ feedInfo.getFeedId());
			} else {
				resp.sendError(401);
				return;
			}
		} catch (Exception e) {
			Utils.throwIfDevelopment(e);
		} finally {
			feedInfoRepo.close();
			feedResultRepo.close();
		}
		resp.sendRedirect("/settings/listfeed.jsp");
	}
}
